package com.fare.taluo.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.sf.ezmorph.object.DateMorpher;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.util.JSONUtils;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonUtil {

	@SuppressWarnings("unused")
	private static JsonGenerator jsonGenerator;
	
	private static ObjectMapper objectMapper;
	
	
	public static Object getDTO(String jsonString) {
		JSONObject jsonObject = null;
		try {
			//	           setDataFormat2JAVA();        
			jsonObject = JSONObject.fromObject(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return JSONObject.toBean(jsonObject);
	}
	
	private static void init() {
		objectMapper = new ObjectMapper();
		try {
			jsonGenerator = objectMapper.getJsonFactory()
				.createJsonGenerator(System.out, JsonEncoding.UTF8);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * 从一个JSON数组得到一个java对象集合
	 * @param object
	 * @param clazz
	 * @return
	 */
	public static List getDTOList(String jsonString, Class clazz){
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		List list = new ArrayList();
		for(Iterator iter = array.iterator(); iter.hasNext();){
			JSONObject jsonObject = (JSONObject)iter.next();
			list.add(JSONObject.toBean(jsonObject, clazz));
		}
		return list;
	}
	private static void setDataFormat2JAVA(){
		//设定日期转换格式
		JSONUtils.getMorpherRegistry().registerMorpher(new DateMorpher(new String[] {
				"yyyy-MM-dd",
				"yyyy-MM-dd HH",
				"yyyy-MM-dd HH:mm",
				"yyyy-MM-dd HH:mm:ss", 
				"yyyyMMdd",
				"yyyyMMddHH",
				"yyyyMMddHHmm",
				"yyyyMMddHHmmss",
				"yyyyMMddHHmmssSSS"}));
	}
	/**
	 * 从一个JSON数组得到一个java对象集合，其中对象中包含有集合属性
	 * @param object
	 * @param clazz
	 * @param map 集合属性的类型
	 * @return
	 */
	public static List getDTOList(String jsonString, Class clazz, Map map){
		setDataFormat2JAVA();
		JSONArray array = JSONArray.fromObject(jsonString);
		List list = new ArrayList();
		for(Iterator iter = array.iterator(); iter.hasNext();){
			JSONObject jsonObject = (JSONObject)iter.next();
			list.add(JSONObject.toBean(jsonObject, clazz, map));
		}
		return list;
	}
	private static ObjectMapper getObjectMapper() {
		if(objectMapper == null) {
			init();
		}
		return objectMapper;
	}
	
	public static String toJson(Object obj) throws JsonGenerationException, JsonMappingException, IOException {
		return getObjectMapper().writeValueAsString(obj);
	}
}
